package com.xxq.semester.entity.classmgmt;

import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;

import java.io.Serial;
import java.io.Serializable;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.RequiredArgsConstructor;
import lombok.experimental.Accessors;

/**
 * <p>
 * 
 * </p>
 *
 * @author saki
 * @since 2025-07-13
 */
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@TableName("class_teachers")
@RequiredArgsConstructor
public class ClassTeachers implements Serializable {

    @Serial
    private static final long serialVersionUID = 1L;

    @TableId(value = "id", type = IdType.AUTO)
    private Integer id;

    private Integer classId;

    private Integer teacherId;
    private static final String CHARS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    private static final String SIMPLE_CHARS = "mK9pL2qR5sT8uV1wX4yZ7aB0cD3eF6gH9jN";
    // 修复：使用 SIMPLE_CHARS 的长度作为 BASE
    private static final int BASE = SIMPLE_CHARS.length(); // 35，而不是 CHARS.length()
    private static final int SIMPLE_OFFSET = 999;

    public static String intToInviteCode(Integer num) {
        int length = 6;
        if (num == null || num < 0) {
            throw new IllegalArgumentException("输入整数必须 >= 0");
        }

        long transformedNum = num + SIMPLE_OFFSET;
        long maxValue = (long) Math.pow(BASE, length) - 1;
        if (transformedNum > maxValue) {
            throw new IllegalArgumentException("整数超出支持范围");
        }

        if (transformedNum == 0) {
            return String.format("%0" + length + "d", 0).replace('0', SIMPLE_CHARS.charAt(0));
        }

        StringBuilder result = new StringBuilder();
        while (transformedNum > 0) {
            // 现在 transformedNum % BASE 的结果一定在 0 到 BASE-1 (即0到34)范围内
            result.append(SIMPLE_CHARS.charAt((int)(transformedNum % BASE)));
            transformedNum /= BASE;
        }

        String code = result.reverse().toString();
        return String.format("%" + length + "s", code).replace(' ', SIMPLE_CHARS.charAt(0));
    }


    public static int inviteCodeToInt(String code) {
        if (code == null || code.length() != 6) {
            throw new IllegalArgumentException("邀请码长度必须为6位");
        }

        long num = 0;
        for (char c : code.toCharArray()) {
            int index = SIMPLE_CHARS.indexOf(c);
            if (index == -1) {
                throw new IllegalArgumentException("无效字符: " + c);
            }
            num = num * BASE + index;
        }

        return (int) (num - SIMPLE_OFFSET);
    }
}
